package handler

import (
	"context"
	"go-likaladi-shop/common/base_global"
	"go-likaladi-shop/common/base_util"
	"google.golang.org/protobuf/types/known/emptypb"
	"lw-shop/goods_service/model"
	"lw-shop/goods_service/proto"
)

func (s *GoodsService) BannerList(context.Context, *emptypb.Empty) (*proto.BannerListResponse, error) {
	bannerListResponse := proto.BannerListResponse{}
	var banners []model.Banner
	result := base_global.DB.Find(&banners)
	if result.Error != nil {
		return nil, base_util.GrpcError(result.Error)
	}

	bannerListResponse.Total = int32(result.RowsAffected)
	var bannerReponses []*proto.BannerResponse
	for _, banner := range banners {
		bannerReponses = append(bannerReponses, &proto.BannerResponse{
			Id:    banner.ID,
			Image: banner.Image,
			Index: banner.Index,
			Url:   banner.URL,
		})
	}
	bannerListResponse.Data = bannerReponses
	return &bannerListResponse, nil
}
func (s *GoodsService) CreateBanner(ctx context.Context, req *proto.BannerRequest) (*proto.BannerResponse, error) {
	banner := model.Banner{}
	banner.Image = req.Image
	banner.Index = req.Index
	banner.URL = req.Url
	//insert into xx
	if result := base_global.DB.Save(&banner); result.Error != nil {
		return nil, base_util.GrpcError(result.Error)
	}
	return &proto.BannerResponse{
		Id:    banner.ID,
		Index: banner.Index,
		Image: banner.Image,
		Url:   banner.URL,
	}, nil
}

func (s *GoodsService) DeleteBanner(ctx context.Context, req *proto.BannerRequest) (*emptypb.Empty, error) {
	//delete from xx where id = req.id
	result := base_global.DB.Delete(&model.Banner{}, req.Id)
	if result.Error != nil {
		return nil, base_util.GrpcError(result.Error)
	}
	if result.RowsAffected == 0 {
		return nil, base_util.LogicError("轮播图不存在")
	}
	return &emptypb.Empty{}, nil
}

func (s *GoodsService) UpdateBanner(ctx context.Context, req *proto.BannerRequest) (*emptypb.Empty, error) {
	var banner model.Banner
	//select * from xx where id = req.id
	if result := base_global.DB.First(&banner, req.Id); result.RowsAffected == 0 {
		return nil, base_util.LogicError("轮播图不存在")
	}
	if req.Url != "" {
		banner.URL = req.Url
	}
	if req.Image != "" {
		banner.Image = req.Image
	}
	if req.Index != 0 {
		banner.Index = req.Index
	}
	base_global.DB.Save(&banner)
	return &emptypb.Empty{}, nil
}
